package com.example.basewarehouse.net;


import android.util.Log;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

/**
 * https://blog.csdn.net/yuzhiqiang666/article/details/51539708
 */
public class RetryWithDelay implements Function<Observable<? extends Throwable>, Observable<?>> {

    private final int maxRetries;
    private final int retryDelayMillis;
    private int retryCount;

    /**
     * 总共重试3次，重试间隔3000毫秒
     * @param maxRetries
     * @param retryDelayMillis
     */
    public RetryWithDelay(int maxRetries, int retryDelayMillis) {
        this.maxRetries = maxRetries;
        this.retryDelayMillis = retryDelayMillis;
    }

    @Override
    public Observable<?> apply(Observable<? extends Throwable> observable) {
        return observable
                .flatMap(new Function<Throwable, ObservableSource<?>>() {
                    @Override
                    public ObservableSource<?> apply(Throwable throwable) throws Exception {
                        if (++retryCount <= maxRetries) {
                            // When this Observable calls onNext, the original Observable will be retried (i.e. re-subscribed).
                            Log.d("Thread","retryCount==========================="+retryCount );
//                            return Observable.timer(retryDelayMillis,
//                                    TimeUnit.MILLISECONDS);
                            return Observable.just(1).delay(retryDelayMillis, TimeUnit.MILLISECONDS);
                        }
                        // Max retries hit. Just pass the error along.
                        return Observable.error(new HttpException(-1,"网络连接失败"));
                    }
                });
    }
}
